package cn.edu.nju.newsFeed;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.edu.nju.R;
import cn.edu.nju.storage.StoreDataProvider;

import android.R.integer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.Display;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;

public class NewsFeedItem extends FeedItem {
	private Bitmap previewImage;
	private int imageNumber;
	private int commentsNumber;
	private List<CommentItem> comments = null;
	
	Activity activity;
	String serverUrl;

	public NewsFeedItem(long postUserId, long postId, Bitmap avatar,
			String postUserName, String postContent, Calendar time,
			Bitmap previewImage, int imageNumber, int likeNumber,
			int commentsNumber, Activity activity) {
		super(postUserId, postId, avatar, postUserName, postContent, time,
				likeNumber,activity);
		this.previewImage = previewImage;
		this.imageNumber = imageNumber;
		this.commentsNumber = commentsNumber;
		this.activity = activity;
		serverUrl = activity.getString(R.string.server_url) + "comments.php";
	}

	public int getCommentsNumber() {
		return commentsNumber;
	}

	public Bitmap getPreviewImage() {
		return previewImage;
	}

	public int getImageNumber() {
		return imageNumber;
	}

	// lazy init
	public Bitmap getImage(int index) {
			try {
				HttpClient client = new DefaultHttpClient();
				HttpContext localContext = new BasicHttpContext();
				HttpPost post = new HttpPost(serverUrl);

				MultipartEntity entity = new MultipartEntity(
						HttpMultipartMode.BROWSER_COMPATIBLE);
				entity.addPart("id", new StringBody("" + postId));
				entity.addPart("option", new StringBody("image"));
				entity.addPart("number", new StringBody("" + index));

				post.setEntity(entity);

				HttpResponse response = client.execute(post, localContext);
				HttpEntity httpEntity = response.getEntity();
				InputStream input = httpEntity.getContent();

				Bitmap bitmap = BitmapFactory.decodeStream(input);
				int width = bitmap.getWidth();
				int height = bitmap.getHeight();
				
				Display display = activity.getWindowManager().getDefaultDisplay();

				int width_display = display.getWidth();
				int height_display = display.getHeight();
				
				float i = 1;
				while(true){
					if(width * i < width_display && height * i < height_display){
						break;
					}
					
					i *= 0.8f;
				}

				Matrix matrix = new Matrix();
				matrix.postScale(i, i);
				matrix.postRotate(0);

				return Bitmap.createBitmap(bitmap, 0, 0, width, height,
						matrix, true);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return null;

	}

	@Override
	public void addOneLike() {
		try {
			String url = activity.getString(R.string.server_url)
					+ "addLike.php";
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(url);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			
			entity.addPart("id", new StringBody("" + StoreDataProvider.getInstance(activity).getUserId()));
			entity.addPart("object_id", new StringBody("" + postId));
			entity.addPart("isComment", new StringBody("0"));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			if (context.equals(new String("OK"))) {
				super.addOneLike();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// get local comments not the latest one
	public List<CommentItem> getComments() {
		if (comments == null) {
			refresh();
		}
		return comments;
	}

	// get the latest data from server
	public void refresh() {
		refreshExceptComments();
		this.comments = new ArrayList<CommentItem>();
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + postId));
			entity.addPart("option", new StringBody("all"));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			if (context != "none") {
				JSONArray jsonArray = new JSONArray(context);

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					long postUserId = object.getLong("owner_id");
					long postId = object.getLong("id");
					Bitmap avatar = getSpecificAvatar(postUserId);
					String postUserName = getSpecificName(postUserId);
					String postContent = object.getString("content");
					
					
					
					String time = object.getString("time_release");
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					Date date = dateFormat.parse(time);
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date);
					
					int likeNumber = object.getInt("num_like");

					comments.add(new CommentItem(postUserId, postId, avatar,
							postUserName, postContent, calendar, likeNumber,activity));
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Bitmap getSpecificAvatar(long postUserId) {
		try {
			String url = activity.getString(R.string.server_url) + "avatar.php";
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(url);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + postUserId));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();

			return BitmapFactory.decodeStream(input);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public String getSpecificName(long postUserId) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + postUserId));
			entity.addPart("option", new StringBody("name"));
			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			return context;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "123";
	}

	// get the latest comments number and like number, but no comments
	public void refreshExceptComments() {
		this.commentsNumber = getCommentsNum();
		this.likeNumber = getLikeNum();
	}

	private int getCommentsNum() {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + postId));
			entity.addPart("option", new StringBody("num_comment"));
			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			return Integer.parseInt(context);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	private int getLikeNum() {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + postId));
			entity.addPart("option", new StringBody("num_like"));
			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			return Integer.parseInt(context);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	// user add a comment to this news feed
	public void addComment(CommentItem comment) {
		this.commentsNumber++;
		this.comments.add(comment);
		// TODO update server
	}

	public long getId() {
		return postId;
	}
}
